package com.sean;
import com.mongodb.*;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Projections;
import org.bson.Document;

import java.util.ArrayList;
import java.util.List;

import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Updates.*;

public class MongoConnection {
    private MongoClient mongoClient;
    private MongoDatabase database;
    public MongoCollection<Document> collection;

    public MongoConnection(){ }

    public void initConnection(String dbName, String collectionName){
        MongoClientURI connectionString = new MongoClientURI("mongodb://localhost:27017");
        // MongoClient mongoClient = new MongoClient("localhost" , 27017);
        mongoClient = new MongoClient(connectionString);
        database = mongoClient.getDatabase(dbName);
        collection = database.getCollection(collectionName);
    }

    public List<String> getAllDocs(){
        ArrayList<String> docList = new ArrayList<String>();
        MongoCursor<Document> cursor = collection.find().projection(Projections.include("tag","imgID","imgURL")).iterator();
        try {
            while (cursor.hasNext()) {
                docList.add(cursor.next().toJson());
                //System.out.println(cursor.next().toJson());
            }
        } finally {
            cursor.close();
        }

        return docList;
    }

//    public String test(){
//       return collection.find().first().toJson();
//    }

    public static void main(String[] args) {
        MongoConnection connect = new MongoConnection();
        connect.initConnection("SinaNewsData", "soccer");

        //Document myDoc = connect.collection.find().first();


//        BasicDBObject query = new BasicDBObject();
//        BasicDBObject fields = new BasicDBObject("_id", "1");

        Document myDoc = connect.collection.find().projection(Projections.include("tag","imgID","imgURL")).first();

        System.out.println(myDoc.toJson());
    }
}

